package com.sb;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

import net.neoremind.sshxcute.core.*;
import net.neoremind.sshxcute.exception.TaskExecFailException;
import net.neoremind.sshxcute.task.CustomTask;
import net.neoremind.sshxcute.task.impl.ExecCommand;

/**
 * 
 * @author sbrito
 * 
 */
public class RunTestScript
{

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		if (args.length != 4)
		{
			System.out.println("Invalid Arguments.\n\nUsage: com.sb.RunTestScript <hostname> <username> <password> <commands file>");
			System.exit(0);
		}
		for (String arg : args)
		{
			if (arg.length() <= 2)
			{
				System.out.println("Invalid Argument: " + arg);
				System.exit(0);
			}
		}
		String hostname = args[0];
		String username = args[1];
		String password = args[2];
		String commandsFile = args[3];

		File f = new File(commandsFile);
		if (!f.exists() || !f.canRead())
		{
			System.out.println("Cannot read file: " + commandsFile);
			System.exit(0);
		}
		SSHExec ssh = null;
		try
		{
			SSHExec.setOption(IOptionName.HALT_ON_FAILURE, false);
			SSHExec.setOption(IOptionName.SSH_PORT_NUMBER, 22);
			// SSHExec.setOption(IOptionName.ERROR_MSG_BUFFER_TEMP_FILE_PATH,
			// "buffer.tmp");
			SSHExec.setOption(IOptionName.INTEVAL_TIME_BETWEEN_TASKS, 10);
			SSHExec.setOption(IOptionName.TIMEOUT, 7000);// 7 sec timeout
			SSHExec.showEnvConfig();

			ConnBean cb = new ConnBean(hostname, username, password);
			ssh = SSHExec.getInstance(cb);
			try
			{
				ssh.connect();
				System.out.println("Connected to "+hostname+"\n");
			}
			catch (Exception ex)
			{
				System.out.println("Failed to connect to "+hostname);
				 System.exit(0);
			}
			 
			
			FileInputStream fstream = new FileInputStream(commandsFile);
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String command;
			CustomTask task;
			Result result;
			while ((command = br.readLine()) != null)
			{
				if (command.trim().length() == 0)
					continue;
				task = new ExecCommand(command);
				result = ssh.exec(task);
				//System.out.println("Executing command: " + task.getCommand());
				result.display();
			}
			br.close();
		}
		catch (TaskExecFailException e)
		{
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		catch (Exception e)
		{
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		finally
		{
			ssh.disconnect();
			new File("TestOverSSH.err").delete();
			new File("TestOverSSH.log").delete();
		}

	}

}
